﻿using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk.Query;
using isky.Plugin;

namespace isky.plugin
{
    public class SalesorderPlugin : IPlugin
    {
        /// <summary>
        /// 订单创建触发事件
        /// </summary>
        /// <param name="serviceProvider"></param>
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context service from the service provider.
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            // Obtain the Organization Service factory service from the service provider
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = factory.CreateOrganizationService(context.UserId);
            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity inputEntity = context.InputParameters["Target"] as Entity;
                    //EntityReference customerId = inputEntity.GetAttributeValue<EntityReference>("customerid");
                    //if (customerId != null)
                    //{
                    //    EntityCollection accountInfo = GetAccountInfo(service, customerId.Id);
                    //    if (accountInfo == null) return;
                    //    var ws_quyu = accountInfo.Entities[0].GetAttributeValue<OptionSetValue>("new_quyu").Value;
                    //    string quyu = QuyuopValue(ws_quyu);
                    //    if (quyu == "") { new Exception("区域不存在！"); }
                    //    EntityCollection trritory = GetTerritoryfo(service);
                    //    if (trritory == null) return;
                    //    foreach (var tryrItem in trritory.Entities)
                    //    {
                    //        if (tryrItem.GetAttributeValue<string>("name") == quyu)
                    //        {
                    //            var manageridEntity = tryrItem.GetAttributeValue<EntityReference>("managerid");
                    //            if (manageridEntity != null)
                    //            {
                    //                GrantAccessRequest grantAccessRequest = new GrantAccessRequest()
                    //                {
                    //                    Target = new EntityReference(context.PrimaryEntityName.ToLower(), context.PrimaryEntityId),//共享的目标实体
                    //                    PrincipalAccess = new PrincipalAccess()
                    //                    {
                    //                        Principal = manageridEntity,//共享的团队
                    //                        AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess //共享读权限
                    //                    }
                    //                };
                    //                service.Execute(grantAccessRequest);
                    //            }
                    //        }
                    //    }
                    //}

                    if (inputEntity.Contains("new_status") 
                        && inputEntity.GetAttributeDefaultValue<OptionSetValue>("new_status", null)!=null
                        && inputEntity.GetAttributeDefaultValue<OptionSetValue>("new_status", null).Value== 100000003)
                    {
                        EntityCollection teamCollection= GetTeamsInfo(service,inputEntity.GetAttributeDefaultValue<OptionSetValue>("new_status", null).Value);
                        if (teamCollection != null)
                        {
                            teamCollection.Entities.ToList().ForEach(tryItem =>
                            {

                                GrantAccessRequest grantAccessRequest = new GrantAccessRequest()
                                {
                                    Target = new EntityReference(context.PrimaryEntityName.ToLower(), context.PrimaryEntityId),//共享的目标实体
                                    PrincipalAccess = new PrincipalAccess()
                                    {
                                        //Principal = new EntityReference(
                                        //   tryItem.GetAttributeValue<EntityReference>("team").LogicalName,
                                        //   tryItem.GetAttributeValue<EntityReference>("team").Id),//共享的团队


                                        //AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess//共享的权限

                                        Principal = tryItem.ToEntityReference(),//共享的团队
                                        AccessMask = AccessRights.ReadAccess //共享读权限
                                    }
                                };
                                service.Execute(grantAccessRequest);

                            });
                        }
                    }


                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
                throw new NotImplementedException();
            }
        }

        /// <summary>
        /// 客户区域选项集
        /// </summary>
        /// <param name="ws_quyu"></param>
        /// <returns></returns>
        private static string QuyuopValue(int ws_quyu)
        {
            string quyu = "";
            if (ws_quyu == 100000000) { quyu = "亚太"; }
            else if (ws_quyu == 100000002) { quyu = "欧非"; }
            else if (ws_quyu == 100000003) { quyu = "南美"; }
            else if (ws_quyu == 100000004) { quyu = "北美"; }
            else if (ws_quyu == 100000001) { quyu = "全球性客户"; }
            else if (ws_quyu == 100000005) { quyu = "中国"; }
            else { quyu = ""; }

            return quyu;
        }



        public static EntityCollection GetTeamsInfo(IOrganizationService service, int areaId)
        {
            EntityCollection result = new EntityCollection();
            var query = CrmQuery.Select(new ColumnSet(true))
                        .From("team")
                        .Where("team", "new_are", ConditionOperator.Equal, new object[] { areaId })
                        .Query;
            result = service.RetrieveMultiple(query);
            if (result != null
                && result.Entities != null
                && result.Entities.Count > 0)
            {
                return result;
            }
            return null;
        }




        /// <summary>
        /// 会员ID 查询会员信息
        /// </summary>
        /// <param name="service"></param>
        /// <param name="accountid"></param>
        /// <returns></returns>
        public static EntityCollection GetAccountInfo(IOrganizationService service, Guid accountid)
        {
            EntityCollection result = new EntityCollection();
            var query = CrmQuery.Select(new ColumnSet("new_quyu"))
                        .From("account")
                        .Where("account", "accountid", ConditionOperator.Equal, new object[] { accountid })
                        .Query;
            result = service.RetrieveMultiple(query);
            if (result != null
                && result.Entities != null
                && result.Entities.Count > 0)
            {
                return result;
            }
            return null;
        }
        /// <summary>
        /// 查询所有区域经理和区域名称
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        public static EntityCollection GetTerritoryfo(IOrganizationService service)
        {
            EntityCollection result = new EntityCollection();
            var query = CrmQuery.Select(new ColumnSet("managerid", "name"))
                        .From("territory")
                        .Query;
            result = service.RetrieveMultiple(query);
            if (result != null
                && result.Entities != null
                && result.Entities.Count > 0)
            {
                return result;
            }
            return null;
        }


    }
}
